<template>
  <el-card class="box-card" v-if="paper" style="border-radius: 20px">
    <template #header>
      <div class="card-header">
        <el-row>
          <el-col :span="20">
            <span>编辑试卷</span>
            <el-button v-if="showSaveToFileBtn" style="margin-left: 3vw" type="success" @click="saveQuestionToFile">
              保存试卷
            </el-button>
            <span v-if="showSaveToFileBtn"><el-icon style="color: orange"><BellFilled/></el-icon>修改完别忘了保存哦</span>
          </el-col>
          <el-col :span="4" style="text-align: right">
            <el-button type="default" round @click="setEditPage">退出</el-button>
          </el-col>
        </el-row>

      </div>
    </template>
    <div class="text item">
      <el-row>
        <el-col :span="5">
          <el-row>
            <el-col :span="24">
              <label>修改试卷基本信息</label>
            </el-col>
          </el-row>
          <el-row style="overflow:scroll;height: 70vh">
            <el-col :span="24">
              <el-form :model="paper">
                <el-form-item label="题库" required>
                  <el-select v-model="paper.database" class="m-2" placeholder="Select">
                    <el-option v-for="item in databaseList" :key="item" :label="item" :value="item"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="试卷名称" required>
                  <el-input v-model="paper.name" placeholder="请输入"/>
                </el-form-item>
                <el-form-item label="考试时长" required>
                  <el-input v-model="paper.duration" type="number" min="0" placeholder="单位：分钟"/>
                </el-form-item>
                <el-form-item label="发布日期">
                  <el-col :span="24">
                    <el-date-picker
                        v-model="paper.exam_date"
                        type="date"
                        placeholder="选择时间"
                        style="width: 100%"
                    />
                  </el-col>
                </el-form-item>
                <el-form-item label="增加题目" v-if="paper">
                  <el-row>
                    <el-col :span="14">
                      <el-select v-model="addQNum" class="m-2" placeholder="请选择">
                        <el-option label="单选题" value="1"/>
                        <el-option label="多选题" value="2"/>
                        <el-option label="简答题" value="3"/>
                        <el-option label="判断题" value="4"/>
                      </el-select>
                    </el-col>
                    <el-col :span="10" style="text-align: right">
                      <el-button @click="addQ" type="primary" round>+</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="编辑题型说明" v-if="paper">

                </el-form-item>
                <div class="mg" v-if="paper" v-for="(item,index) in paper.question_type">

                  <el-input v-model="item.description" placeholder="例：一、单选题（1.5分/题）"
                            @input="showSaveToFileBtn = true">
                    <template #prepend v-if="item.type_number === '1'">单选题</template>
                    <template #prepend v-if="item.type_number === '2'">多选题</template>
                    <template #prepend v-if="item.type_number === '3'">简答题</template>
                    <template #prepend v-if="item.type_number === '4'">判断题</template>
                  </el-input>
                </div>
              </el-form>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="5" :offset="1">
          <el-row>
            <el-col :span="24">
              <label>当前试卷下的题目</label>
            </el-col>
          </el-row>
          <el-row style="overflow:scroll;height: 70vh">
            <el-col :span="24">
              <el-row class="mg row" v-for="(item,index) in paper.questions" :key="index">
                <el-col :span="18">
                  <span class="sp">{{ item.question_number }}&nbsp;&nbsp;</span>
                  <el-tag type="success" v-if="item.type_number === '1'">单选</el-tag>
                  <el-tag type="warning" v-if="item.type_number === '2'">多选</el-tag>
                  <el-tag type="info" v-if="item.type_number === '3'">简答</el-tag>
                  <el-tag type="danger" v-if="item.type_number === '4'">判断</el-tag>

                  <p class="label">{{ item.question }}</p>
                  <p class="sp">正确答案：{{ item.right }}</p>
                </el-col>
                <el-col :span="6">
                  <div style="text-align: right;width: 90%;">
                    <el-button type="primary" size="small" round @click="editQuestion(index)">编辑</el-button>
                    <br>
                    <br>
                    <el-button type="primary" size="small" round @click="deleteQuestion(index)">X</el-button>
                  </div>

                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12" :offset="1">
          <el-empty description="未选择题目" v-if="!question"/>
          <el-row v-if="question">
            <el-col :span="24">
              <label>修改题目信息</label>
            </el-col>
          </el-row>
          <el-row style="overflow:scroll;height: 70vh" v-if="question">
            <el-col :span="24">
              <el-form :model="question">
                <el-form-item label="题目内容" required>
                  <el-input v-model="question.question" :rows="2" type="textarea" placeholder="请输入"/>
                </el-form-item>
                <el-form-item label="选择模块">
                  <el-select v-model="question.question_module" placeholder="请选择" @change="updateModule" @click="getOldValue">
                    <el-option :label="item.module" :value="item.module" v-for="(item,index) in modules" :key="index"/>
                  </el-select>
                  <el-tooltip class="box-item" effect="dark" content="新增模块" placement="top-start">
                    <el-button type="default" @click="showAddModule = true">+</el-button>
                  </el-tooltip>
                  <el-tooltip class="box-item" effect="dark" content="删除当前选中模块" placement="right-start">
                    <el-button type="default" v-if="question.question_module" @click="deleteModule">-</el-button>
                  </el-tooltip>
                  <br>
                  <el-input class="mg" v-model="newModuleName" v-if="showAddModule"  placeholder="请输入模块名称" style="width: 40%"/>
                  <el-tooltip class="box-item" effect="dark" content="确认" placement="right-start" v-if="showAddModule">
                    <el-button class="mg" type="default" v-if="showAddModule" @click="comfirmNewModule"><el-icon><Select /></el-icon></el-button>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="设置分数">
                  <el-input-number v-model="question.score" placeholder="请输入分数" style="width: 40%" :min="0"/>
                </el-form-item>
                <el-form-item label="设置选项数量" v-if="question.type_number === '1' || question.type_number === '2'">
                  <el-input-number v-model="optionLength" placeholder="请输入选项数量：最大10" style="width: 40%"
                                   :min="0" :max="10" @change="initanswer" @input="initanswer"/>
                </el-form-item>
                <el-form-item label="设置选项" v-if="question.type_number === '1' || question.type_number === '2'">
                  <el-row class="mg" v-for="item in optionLength" :key="item">
                    <el-col :span="24">
                      <el-input v-model="question.answer[item-1].text" placeholder="请输入">
                        <template #prepend>选项：{{ alphabet[item - 1] }}</template>
                      </el-input>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="设置正确答案">
                  <el-radio-group v-model="question.right[0]" class="ml-4" v-if="question.type_number === '1'">
                    <el-radio class="mg" :label="alphabet[item-1]" size="default" border
                              v-for="item in Number(optionLength)" :key="item"/>
                  </el-radio-group>

                  <el-checkbox v-if="question.type_number === '2'" v-model="question.right[item-1]"
                               :label="alphabet[item-1]" class="mg" size="default" border
                               v-for="item in Number(optionLength)" :key="item"/>

                  <el-input v-model="question.right[0]" v-if="question.type_number === '3'" :rows="2" type="textarea"
                            placeholder="请输入答案"/>

                  <el-radio-group v-model="question.right[0]" class="ml-4" v-if="question.type_number === '4'">
                    <el-radio class="mg" label="A" size="default" border>正确</el-radio>
                    <el-radio class="mg" label="B" size="default" border>错误</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="设置解析">
                  <el-input v-model="question.correct_answer" :rows="2" type="textarea" placeholder="请输入解析"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveQuestion">保存题目</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

    </div>
  </el-card>
  <button @click="test">123</button>
  <el-dialog
      v-model="dialogVisible"
      title="提示"
      width="20%"
      :before-close="handleClose" style="border-radius: 20px"
  >
    <span>确定要删除吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="comfirmDelete">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {defineProps, onMounted, ref, toRefs, watch} from 'vue'
import {ElNotification} from 'element-plus'
import useDatabaseStore from "../../store/databaseStore";
import useShowPageStore from "../../store/showPageStore"

const sp = useShowPageStore()
const st = useDatabaseStore()
const props = defineProps({
  fName: String,
})
const {fName} = toRefs(props)
const paper = ref()
const databaseList = ref([])
const question = ref()
const optionLength = ref(0)
const questionIndex = ref(0)
const qindex = ref(0)
const showSaveToFileBtn = ref(false)
const alphabet = Array.from({length: 26}, (_, i) => String.fromCharCode(65 + i));
const dialogVisible = ref(false)

const addQNum = ref("")
const showAddModule = ref(false)
const newModuleName = ref("")
const modules = ref([])
const question_module = ref("")
const oldModule = ref("")

let modulesData = []


const getOldValue = () => {
  oldModule.value = question.value.question_module
}

const updateModule = () => {
  console.log(oldModule.value)
  if (localStorage.getItem("modules")){
    modulesData = JSON.parse(localStorage.getItem("modules"))
    for (let i = 0; i < modulesData.length; i++) {
      if(modulesData[i].module === oldModule.value){
        if (modulesData[i].count > 0){
          modulesData[i].count--
        }
      }
      else if (modulesData[i].module === question.value.question_module){
        modulesData[i].count++
      }
    }
  }
  
}

const test = () => {
  console.log(modulesData)
}

const deleteModule = () => {
  let modules = JSON.parse(localStorage.getItem("modules"))
  for (let i = 0; i < modules.length; i++) {
    if (modules[i].module === question.value.question_module){
      modules.splice(i,1)
      myApi.alert("模块删除成功","info")
    }
  }
  localStorage.removeItem("modules")
  localStorage.setItem("modules",JSON.stringify(modules))
}

const comfirmNewModule = () => {
  if (localStorage.getItem("modules")){
    let modules = JSON.parse(localStorage.getItem("modules"))
    modules.push({"module": newModuleName.value,"count": 0})
    localStorage.removeItem("modules")
    localStorage.setItem("modules",JSON.stringify(modules))
  }
  else {
    let data = {"module": newModuleName.value,"count": 0}
    localStorage.setItem("modules",JSON.stringify([data]))
  }
  modules.value = JSON.parse(localStorage.getItem('modules'))
  showAddModule.value = false
  question.value.question_module = newModuleName.value
  newModuleName.value = ""
  myApi.alert("模块添加成功","info")
}

const addQ = () => {
  let num = ""
  if (addQNum.value === "1") {
    num = "1"
  } else if (addQNum.value === "2") {
    num = "2"
  } else if (addQNum.value === "3") {
    num = "3"
  } else if (addQNum.value === "4") {
    num = "4"
  }
  let question = {
    "type_number": num,
    "question_number": paper.value.questions.length + 1,
    "question_module": "",
    "score": 0,
    "question": "",
    "answer": [],
    "right": [],
    "correct_answer": ""
  }
  paper.value.questions.push(question)
  notification("添加成功啦", "success")
  let add_able = true
  for (let i = 0; i < paper.value.question_type.length; i++) {
    if (paper.value.question_type[i].type_number === num) {
      add_able = false
      return
    }
  }
  if (add_able) {
    let type = {"type_number": num, "description": ""}
    paper.value.question_type.push(type)
  }
  paper.value.question_type.sort((a, b) => a.type_number - b.type_number);
}

watch([() => fName.value, () => optionLength.value  ], ([newValue1, newValue2], [oldValue1, oldValue2]) => {
      // 处理值变化的逻辑
      if (newValue1 !== oldValue1) {
        getPaper()
        showSaveToFileBtn.value = false
      }
      if (newValue2 !== oldValue2) {
        if (newValue2 > 10) {
          optionLength.value = 10
        } else if (newValue2 < 0) {
          optionLength.value = 0
        }
      }
    }
);

onMounted(() => {
  getPaper()
  if (st.result) {
    for (let i = 0; i < st.result.dbs.length; i++) {
      databaseList.value.push(st.result.dbs[i].database)
    }
    databaseList.value = [...new Set(databaseList.value)];
  }
  modules.value = JSON.parse(localStorage.getItem('modules'))
})

const getPaper = async () => {
  const res = await myApi.getPaper(fName.value)
  paper.value = res
}

const editQuestion = (index) => {
  questionIndex.value = index
  question.value = paper.value.questions[index]
  question_module.value = question.value.question_module
  optionLength.value = question.value.answer.length

  if (question.value.type_number === "2") {
    if (!question.value.right.includes(true)) {
      let tempList = new Array(optionLength.value).fill(0)
      const result = tempList.map((value, index) => alphabet[index]);
      question.value.right = result.map(value => question.value.right.includes(value) ? true : false);
    }
  }
  question_module.value = ""
}

const initanswer = () => {
  if (optionLength.value > question.value.answer.length) {
    for (let i = 0; i <= optionLength.value - question.value.answer.length; i++) {
      question.value.answer.push({"option": alphabet[i + question.value.answer.length], "text": ""})
    }
  } else if (optionLength.value < question.value.answer.length) {
    for (let i = 0; i <= question.value.answer.length - optionLength.value; i++) {
      question.value.answer.pop()
    }
  }
}

const saveQuestion = () => {
  if (paper.value.name === "") {
    myApi.alert("请先填写试卷名称", "info")
    return
  } else if (paper.value.duration <= 0) {
    myApi.alert("请先设置考试时长", "info")
    return
  } else if (question.value.question === "") {
    myApi.alert("请先设置题目", "info")
    return
  }
  let filteredResult = []
  if (question.value.type_number === '2') {
    const result = question.value.right.map((value, index) => value ? alphabet[index] : value);
    filteredResult = result.filter(value => value !== false);
  }
  if (filteredResult.length > 0) {
    question.value.right = filteredResult
  }
  paper.value.exam_date = new Date(paper.value.exam_date).toLocaleDateString()
  paper.value.questions[questionIndex.value] = question.value

  showSaveToFileBtn.value = true
  question.value = null
  notification("题目保存成功，所有修改完成后别忘了保存试卷哦*^_^*", "success")
}

const saveQuestionToFile = () => {
  paper.value.question_volume = paper.value.questions.length
  let data_str = JSON.stringify(paper.value)
  myApi.updateJsonFile(fName.value, JSON.parse(data_str))
  myApi.alert("试卷保存成功", "info")
  localStorage.removeItem("modules")
  localStorage.setItem("modules",JSON.stringify(modulesData))
  showSaveToFileBtn.value = false
}

const notification = (msg, type) => {
  ElNotification({
    title: 'TeCool',
    message: msg,
    type: type,
    position: 'top-right',
  })
}


const deleteQuestion = (index) => {
  qindex.value = index
  dialogVisible.value = true
  if (localStorage.getItem("modules")){
    modulesData = JSON.parse(localStorage.getItem("modules"))
  }
}

const handleClose = (done: () => void) => {
  dialogVisible.value = false
  done()
}

const comfirmDelete = () => {
  console.log(paper.value.questions[qindex.value].question_module)
  for (let i = 0; i < modulesData.length; i++) {
    if (modulesData[i].module === paper.value.questions[qindex.value].question_module){
      if (modulesData[i].count > 0){
        modulesData[i].count--
      }
    }
  }
  paper.value.questions.splice(qindex.value, 1)
  dialogVisible.value = false
  showSaveToFileBtn.value = true
  question.value = null
}

const setEditPage = () => {
  sp.setEditPage(false)
}
</script>

<style scoped>
.row {
  background: linear-gradient(90deg, rgba(0, 255, 235, 1) 0%, rgba(129, 193, 222, 1) 100%);
  border-radius: 20px;
  padding: 10px;
}

.sp {
  font-size: smaller;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 90%;
}

.label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 90%;
}
</style>